<!DOCTYPE html>
<html lang=zh>
<head>
    <meta charset="utf-8">
    
    <title>第三十六章：基于SpringBoot架构重写SpringMVC请求参数装载 | 恒宇少年De成长之路</title>
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1" />
    <meta name="description" content="在国内企业开发项目中大多数都已经偏向Spring家族式的开发风格，在前几年国内项目都是以Structs2作为Web开发的主导，不过由于近几年发生的事情确实让开发者对它失去了以往的信心。">
<meta name="keywords" content="SpringBoot">
<meta property="og:type" content="article">
<meta property="og:title" content="第三十六章：基于SpringBoot架构重写SpringMVC请求参数装载">
<meta property="og:url" content="http://blog.yuqiyu.com/spring-boot-chapter-36/index.html">
<meta property="og:site_name" content="恒宇少年De成长之路">
<meta property="og:description" content="在国内企业开发项目中大多数都已经偏向Spring家族式的开发风格，在前几年国内项目都是以Structs2作为Web开发的主导，不过由于近几年发生的事情确实让开发者对它失去了以往的信心。">
<meta property="og:locale" content="zh-CN">
<meta property="og:image" content="http://upload-images.jianshu.io/upload_images/4461954-e0f9d7cfc6f94af7.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">
<meta property="og:image" content="http://upload-images.jianshu.io/upload_images/4461954-1cf288b1ed524fd9.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">
<meta property="og:image" content="http://upload-images.jianshu.io/upload_images/4461954-f1d4cb64234b160a.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">
<meta property="og:updated_time" content="2018-01-23T15:30:10.946Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="第三十六章：基于SpringBoot架构重写SpringMVC请求参数装载">
<meta name="twitter:description" content="在国内企业开发项目中大多数都已经偏向Spring家族式的开发风格，在前几年国内项目都是以Structs2作为Web开发的主导，不过由于近几年发生的事情确实让开发者对它失去了以往的信心。">
<meta name="twitter:image" content="http://upload-images.jianshu.io/upload_images/4461954-e0f9d7cfc6f94af7.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">
    

    
        <link rel="alternate" href="/" title="恒宇少年De成长之路" type="application/atom+xml" />
    

    

    <link rel="stylesheet" href="/libs/font-awesome/css/font-awesome.min.css">
    <link rel="stylesheet" href="/libs/open-sans/styles.css">
    <link rel="stylesheet" href="/libs/source-code-pro/styles.css">

    <link rel="stylesheet" href="/css/style.css">

    <script src="/libs/jquery/2.1.3/jquery.min.js"></script>
    
    
        <link rel="stylesheet" href="/libs/lightgallery/css/lightgallery.min.css">
    
    
        <link rel="stylesheet" href="/libs/justified-gallery/justifiedGallery.min.css">
    
    
    
    


</head>

<body>
    <div id="container">
        <header id="header">
    <div id="header-main" class="header-inner">
        <div class="outer">
            <a href="/" id="logo">
                <i class="logo"></i>
                <span class="site-title">恒宇少年De成长之路</span>
            </a>
            <nav id="main-nav">
                
                    <a class="main-nav-link" href="/.">首页</a>
                
                    <a class="main-nav-link" href="/archives">时间轴</a>
                
                    <a class="main-nav-link" href="/categories">文章专题</a>
                
                    <a class="main-nav-link" href="/tags">标签云</a>
                
                    <a class="main-nav-link" href="/about">关于我</a>
                
            </nav>
            
                
                <nav id="sub-nav">
                    <div class="profile" id="profile-nav">
                        <a id="profile-anchor" href="javascript:;">
                            <img class="avatar" src="/css/images/avatar.png" />
                            <i class="fa fa-caret-down"></i>
                        </a>
                    </div>
                </nav>
            
            <div id="search-form-wrap">

    <form class="search-form">
        <input type="text" class="ins-search-input search-form-input" placeholder="搜索" />
        <!--button type="submit" class="search-form-submit"></button-->
    </form>
    <div class="ins-search">
    <div class="ins-search-mask"></div>
    <div class="ins-search-container">
        <div class="ins-input-wrapper">
            <input type="text" class="ins-search-input" placeholder="想要查找什么..." />
            <span class="ins-close ins-selectable"><i class="fa fa-times-circle"></i></span>
        </div>
        <div class="ins-section-wrapper">
            <div class="ins-section-container"></div>
        </div>
    </div>
</div>
<script>
(function (window) {
    var INSIGHT_CONFIG = {
        TRANSLATION: {
            POSTS: '文章',
            PAGES: '页面',
            CATEGORIES: '分类',
            TAGS: '标签',
            UNTITLED: '(未命名)',
        },
        ROOT_URL: '/',
        CONTENT_URL: '/content.json',
    };
    window.INSIGHT_CONFIG = INSIGHT_CONFIG;
})(window);
</script>
<script src="/js/insight.js"></script>

</div>
        </div>
    </div>
    <div id="main-nav-mobile" class="header-sub header-inner">
        <table class="menu outer">
            <tr>
                
                    <td ><a  class="main-nav-link" href="/.">首页</a></td>
                
                    <td ><a  class="main-nav-link" href="/archives">时间轴</a></td>
                
                    <td ><a  class="main-nav-link" href="/categories">文章专题</a></td>
                
                    <td ><a  class="main-nav-link" href="/tags">标签云</a></td>
                
                    <td ><a  class="main-nav-link" href="/about">关于我</a></td>
                
                <td>
                    
    <div class="search-form">
        <input type="text" class="ins-search-input search-form-input" placeholder="搜索" />
    </div>

                </td>
            </tr>
        </table>
    </div>
</header>

        <div class="outer">
            
                

<aside id="profile">
    <div class="inner profile-inner">
        <div class="base-info profile-block">
            <img id="avatar" src="/css/images/avatar.png" />
            <h2 id="name">恒宇少年</h2>
            <h3 id="title">Java软件工程师 &amp; 程序猿</h3>
            <span id="location"><i class="fa fa-map-marker"></i>山东, 济南</span>
            <a id="follow" target="_blank" href="https://www.jianshu.com/u/092df3f77bca">关注我</a>
        </div>
        <div class="article-info profile-block">
            <div class="article-info-block">
                43
                <span>文章</span>
            </div>
            <div class="article-info-block">
                2
                <span>标签</span>
            </div>
        </div>
        
        <div class="profile-block social-links">
            <table>
                <tr>
                    
                    
                    <td>
                        <a href="http://github.com/ppoffice/hexo-theme-icarus" target="_blank" title="github" class=tooltip>
                            <i class="fa fa-github"></i>
                        </a>
                    </td>
                    
                    <td>
                        <a href="/" target="_blank" title="twitter" class=tooltip>
                            <i class="fa fa-twitter"></i>
                        </a>
                    </td>
                    
                    <td>
                        <a href="/" target="_blank" title="facebook" class=tooltip>
                            <i class="fa fa-facebook"></i>
                        </a>
                    </td>
                    
                    <td>
                        <a href="/" target="_blank" title="dribbble" class=tooltip>
                            <i class="fa fa-dribbble"></i>
                        </a>
                    </td>
                    
                    <td>
                        <a href="/" target="_blank" title="rss" class=tooltip>
                            <i class="fa fa-rss"></i>
                        </a>
                    </td>
                    
                </tr>
            </table>
        </div>
        
    </div>
</aside>

            
            <section id="main"><article id="post-spring-boot-chapter-36" class="article article-type-post" itemscope itemprop="blogPost">
    <div class="article-inner">
        
        
            <header class="article-header">
                
    
        <h1 class="article-title" itemprop="name">
            第三十六章：基于SpringBoot架构重写SpringMVC请求参数装载
        </h1>
    

                
                    <div class="article-meta">
                        
    <div class="article-date">
        <i class="fa fa-calendar"></i>
        <a href="/spring-boot-chapter-36/">
            <time datetime="2017-09-16T16:00:00.000Z" itemprop="datePublished">2017-09-17</time>
        </a>
    </div>


                        
    <div class="article-category">
    	<i class="fa fa-folder"></i>
        <a class="article-category-link" href="/categories/SpringBoot-核心技术/">SpringBoot 核心技术</a>
    </div>

                        
    <div class="article-tag">
        <i class="fa fa-tag"></i>
        <a class="tag-link" href="/tags/SpringBoot/">SpringBoot</a>
    </div>

                    </div>
                
            </header>
        
        
        <div class="article-entry" itemprop="articleBody">
        
            
            <p>在国内企业开发项目中大多数都已经偏向<code>Spring</code>家族式的开发风格，在前几年国内项目都是以<code>Structs2</code>作为<code>Web</code>开发的主导，不过由于近几年发生的事情确实让开发者对它失去了以往的信心。<br><a id="more"></a><br>与此同时<code>Spring</code>家族发布了<code>SpringMVC</code>，而且完美的整合<code>Spring</code>来开发企业级大型<code>Web</code>项目。它有着比<code>Structs2</code>更强大的技术支持以及更灵活的自定义配置，接下来我们就看看本章的内容，我们自定义实现<code>SpringMVC</code>参数绑定规则，根据业务定制参数装载实现方式。</p>
<h1 id="本章目标"><a href="#本章目标" class="headerlink" title="本章目标"></a>本章目标</h1><p>根据项目定制<code>SpringMVC</code>参数状态并了解<code>SpringMVC</code>的装载过程以及实现方式。</p>
<h1 id="SpringBoot-企业级核心技术学习专题"><a href="#SpringBoot-企业级核心技术学习专题" class="headerlink" title="SpringBoot 企业级核心技术学习专题"></a>SpringBoot 企业级核心技术学习专题</h1><table>
<thead>
<tr>
<th style="text-align:center">专题</th>
<th style="text-align:left">专题名称</th>
<th style="text-align:left">专题描述</th>
</tr>
</thead>
<tbody>
<tr>
<td style="text-align:center">001</td>
<td style="text-align:left"><a href="http://www.jianshu.com/c/3f69deddbed3" target="_blank" rel="noopener">Spring Boot 核心技术</a></td>
<td style="text-align:left">讲解SpringBoot一些企业级层面的核心组件</td>
</tr>
<tr>
<td style="text-align:center">002</td>
<td style="text-align:left"><a href="https://gitee.com/hengboy/spring-boot-chapter" target="_blank" rel="noopener">Spring Boot 核心技术章节源码</a></td>
<td style="text-align:left">Spring Boot 核心技术简书每一篇文章码云对应源码</td>
</tr>
<tr>
<td style="text-align:center">003</td>
<td style="text-align:left"><a href="http://www.jianshu.com/c/1faac22666e7" target="_blank" rel="noopener">Spring Cloud 核心技术</a></td>
<td style="text-align:left">对Spring Cloud核心技术全面讲解</td>
</tr>
<tr>
<td style="text-align:center">004</td>
<td style="text-align:left"><a href="https://gitee.com/hengboy/spring-cloud-chapter" target="_blank" rel="noopener">Spring Cloud 核心技术章节源码</a></td>
<td style="text-align:left">Spring Cloud 核心技术简书每一篇文章对应源码</td>
</tr>
<tr>
<td style="text-align:center">005</td>
<td style="text-align:left"><a href="http://www.jianshu.com/c/ab4789177827" target="_blank" rel="noopener">QueryDSL 核心技术</a></td>
<td style="text-align:left">全面讲解QueryDSL核心技术以及基于SpringBoot整合SpringDataJPA</td>
</tr>
<tr>
<td style="text-align:center">006</td>
<td style="text-align:left"><a href="http://www.jianshu.com/c/f1b269bb2fd6" target="_blank" rel="noopener">SpringDataJPA 核心技术</a></td>
<td style="text-align:left">全面讲解SpringDataJPA核心技术</td>
</tr>
</tbody>
</table>
<h1 id="构建项目"><a href="#构建项目" class="headerlink" title="构建项目"></a>构建项目</h1><p>我们先来创建一个<code>SpringBoot</code>项目，添加本章所需的依赖，pom.xml配置文件如下所示：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br></pre></td><td class="code"><pre><span class="line">...//省略部分配置</span><br><span class="line">&lt;dependencies&gt;</span><br><span class="line">        &lt;dependency&gt;</span><br><span class="line">            &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;</span><br><span class="line">            &lt;artifactId&gt;spring-boot-starter-web&lt;/artifactId&gt;</span><br><span class="line">        &lt;/dependency&gt;</span><br><span class="line">        &lt;!-- spring boot tomcat jsp 支持开启 --&gt;</span><br><span class="line">        &lt;dependency&gt;</span><br><span class="line">            &lt;groupId&gt;org.apache.tomcat.embed&lt;/groupId&gt;</span><br><span class="line">            &lt;artifactId&gt;tomcat-embed-jasper&lt;/artifactId&gt;</span><br><span class="line">        &lt;/dependency&gt;</span><br><span class="line">        &lt;!--servlet支持开启--&gt;</span><br><span class="line">        &lt;dependency&gt;</span><br><span class="line">            &lt;groupId&gt;javax.servlet&lt;/groupId&gt;</span><br><span class="line">            &lt;artifactId&gt;javax.servlet-api&lt;/artifactId&gt;</span><br><span class="line">        &lt;/dependency&gt;</span><br><span class="line">        &lt;!-- jstl 支持开启 --&gt;</span><br><span class="line">        &lt;dependency&gt;</span><br><span class="line">            &lt;groupId&gt;javax.servlet&lt;/groupId&gt;</span><br><span class="line">            &lt;artifactId&gt;jstl&lt;/artifactId&gt;</span><br><span class="line">        &lt;/dependency&gt;</span><br><span class="line">        &lt;!--lombok支持--&gt;</span><br><span class="line">        &lt;dependency&gt;</span><br><span class="line">            &lt;groupId&gt;org.projectlombok&lt;/groupId&gt;</span><br><span class="line">            &lt;artifactId&gt;lombok&lt;/artifactId&gt;</span><br><span class="line">        &lt;/dependency&gt;</span><br><span class="line">        &lt;!--fastjson支持--&gt;</span><br><span class="line">        &lt;dependency&gt;</span><br><span class="line">            &lt;groupId&gt;com.alibaba&lt;/groupId&gt;</span><br><span class="line">            &lt;artifactId&gt;fastjson&lt;/artifactId&gt;</span><br><span class="line">            &lt;version&gt;1.2.38&lt;/version&gt;</span><br><span class="line">        &lt;/dependency&gt;</span><br><span class="line">        &lt;dependency&gt;</span><br><span class="line">            &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;</span><br><span class="line">            &lt;artifactId&gt;spring-boot-starter-test&lt;/artifactId&gt;</span><br><span class="line">            &lt;scope&gt;test&lt;/scope&gt;</span><br><span class="line">        &lt;/dependency&gt;</span><br><span class="line">    &lt;/dependencies&gt;</span><br><span class="line">...//省略部分配置</span><br></pre></td></tr></table></figure></p>
<p>本章需要<code>JSP</code>相关的依赖支持，所以需要添加对应的依赖，修改<code>application.properties</code>配置文件让<code>JSP</code>生效，配置内容如下所示：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">spring.mvc.view.prefix=/WEB-INF/jsp/</span><br><span class="line">spring.mvc.view.suffix=.jsp</span><br></pre></td></tr></table></figure></p>
<p>相关<code>JSP</code>配置可以访问<a href="http://www.jianshu.com/p/90a84c814d0c" target="_blank" rel="noopener">第二章：SpringBoot与JSP间不可描述的秘密</a>查看讲解。</p>
<h3 id="SpringMVC的参数装载"><a href="#SpringMVC的参数装载" class="headerlink" title="SpringMVC的参数装载"></a>SpringMVC的参数装载</h3><p>在讲解我们自定义参数装载之前，我们先来看看<code>SpringMVC</code>内部为我们提供的参数装载方式。</p>
<p>######添加测试JSP<br>我们首先来添加一个测试的jsp页面，页面上添加一些输入元素，代码如下所示：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line">&lt;%--</span><br><span class="line">  Created by IntelliJ IDEA.</span><br><span class="line">  User: hengyu</span><br><span class="line">  Date: 2017/9/17</span><br><span class="line">  Time: 10:33</span><br><span class="line">  To change this template use File | Settings | File Templates.</span><br><span class="line">--%&gt;</span><br><span class="line">&lt;%@ page contentType=&quot;text/html;charset=UTF-8&quot; language=&quot;java&quot; %&gt;</span><br><span class="line">&lt;html&gt;</span><br><span class="line">&lt;head&gt;</span><br><span class="line">    &lt;title&gt;Title&lt;/title&gt;</span><br><span class="line">&lt;/head&gt;</span><br><span class="line">&lt;body&gt;</span><br><span class="line">    &lt;form method=&quot;post&quot; action=&quot;/submit&quot;&gt;</span><br><span class="line">        教师姓名：&lt;input type=&quot;text&quot; name=&quot;name&quot;/&gt;&lt;br/&gt;&lt;br/&gt;</span><br><span class="line">        学生姓名：&lt;input type=&quot;text&quot; name=&quot;name&quot;/&gt;&lt;br/&gt;&lt;br/&gt;</span><br><span class="line">        学生年龄：&lt;input type=&quot;text&quot; name=&quot;age&quot;/&gt;&lt;br/&gt;&lt;br/&gt;</span><br><span class="line">        &lt;input type=&quot;submit&quot;/&gt;</span><br><span class="line">    &lt;/form&gt;</span><br><span class="line">&lt;/body&gt;</span><br><span class="line">&lt;/html&gt;</span><br></pre></td></tr></table></figure></p>
<p>在<code>index.jsp</code>内添加了三个<code>name</code>的文本输入框，如果我们现在提交到后台<code>SpringMVC</code>为默认为我们解析成一个数组，如果根据描述而言的来处理则是不合理的，当然也可以使用各种手段完成字段参数的装载，比如：为教师的<code>name</code>添加一个数组或者List集合进行接受，这种方式也是可以实现但<code>不优雅</code>。</p>
<blockquote>
<p>如果你们项目组有严格的开发规范要求，这种方式是不允许出现在<code>Controller</code>方法内的。</p>
</blockquote>
<p>那这个问题就让人头疼了，在之前我们使用<code>Struct2</code>的时候是可以根据指定的前缀，如：<code>xxx.xxx</code>来进行映射的，而<code>SpringMVC</code>并没有提供这个支持，不过它提供了自定义参数装载的实现方法，那就没有问题了，我们可以手写。</p>
<h3 id="自定义的参数装载"><a href="#自定义的参数装载" class="headerlink" title="自定义的参数装载"></a>自定义的参数装载</h3><p>既然上面的代码实现满足不了我们的需求，那么我接下来就来重写参数装载。</p>
<p>#####创建ParameterModel注解<br>对于一直使用<code>SpringMVC</code>的朋友来说，应该对<code>@RequestParam</code>很熟悉，而本章我们自定义的注解跟<code>@RequestParam</code>类似，主要目的也是标识指定参数完成数据的绑定。下面我们先来看看该注解的源码，如下所示：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line">package com.yuqiyu.chapter36.annotation;</span><br><span class="line"></span><br><span class="line">import java.lang.annotation.ElementType;</span><br><span class="line">import java.lang.annotation.Retention;</span><br><span class="line">import java.lang.annotation.RetentionPolicy;</span><br><span class="line">import java.lang.annotation.Target;</span><br><span class="line"></span><br><span class="line">/**</span><br><span class="line"> * 参数实体映射注解</span><br><span class="line"> * 配置该注解的参数会使用 com.yuqiyu.chapter36.resovler.CustomerArgumentResolver类完成参数装载</span><br><span class="line"> * ========================</span><br><span class="line"> * Created with IntelliJ IDEA.</span><br><span class="line"> * User：恒宇少年</span><br><span class="line"> * Date：2017/9/16</span><br><span class="line"> * Time：22:19</span><br><span class="line"> * 码云：http://git.oschina.net/jnyqy</span><br><span class="line"> * ========================</span><br><span class="line"> */</span><br><span class="line">@Target(value = ElementType.PARAMETER)</span><br><span class="line">@Retention(RetentionPolicy.RUNTIME)</span><br><span class="line">public @interface ParameterModel</span><br><span class="line">&#123;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>该注解目前没有添加任何一个属性，这个也是可以根据项目的需求已经业务逻辑进行相应添加的，比如<code>@RequestParam</code>内常用的属性<code>required</code>、<code>defaultValue</code>等属性，由于我们本章内容不需要自定义注解内的属性所以这里就不添加了。</p>
<p>该注解的作用域是在参数上<code>@Target(value = ElementType.PARAMETER)</code>，我们仅可以在方法参数上使用。</p>
<h3 id="创建参数接受实体"><a href="#创建参数接受实体" class="headerlink" title="创建参数接受实体"></a>创建参数接受实体</h3><p>我们可以回到上面看看<code>index.jsp</code>的内容，我们需要教师的基本信息以及学生的基本信息，那我们就为教师、以及学生创建实体（注意：这个实体可以是对应数据库内的实体）</p>
<h6 id="教师实体"><a href="#教师实体" class="headerlink" title="教师实体"></a>教师实体</h6><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line">package com.yuqiyu.chapter36.bean;</span><br><span class="line"></span><br><span class="line">import lombok.Data;</span><br><span class="line"></span><br><span class="line">/**</span><br><span class="line"> * ========================</span><br><span class="line"> * Created with IntelliJ IDEA.</span><br><span class="line"> * User：恒宇少年</span><br><span class="line"> * Date：2017/9/17</span><br><span class="line"> * Time：10:40</span><br><span class="line"> * 码云：http://git.oschina.net/jnyqy</span><br><span class="line"> * ========================</span><br><span class="line"> */</span><br><span class="line">@Data</span><br><span class="line">public class TeacherEntity &#123;</span><br><span class="line">    //教师姓名</span><br><span class="line">    private String name;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>教师实体内目前为了测试就添加一个跟页面参数有关的字段。</p>
<h6 id="学生实体"><a href="#学生实体" class="headerlink" title="学生实体"></a>学生实体</h6><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line">package com.yuqiyu.chapter36.bean;</span><br><span class="line"></span><br><span class="line">import lombok.Data;</span><br><span class="line"></span><br><span class="line">/**</span><br><span class="line"> * ========================</span><br><span class="line"> * Created with IntelliJ IDEA.</span><br><span class="line"> * User：恒宇少年</span><br><span class="line"> * Date：2017/9/17</span><br><span class="line"> * Time：10:41</span><br><span class="line"> * 码云：http://git.oschina.net/jnyqy</span><br><span class="line"> * ========================</span><br><span class="line"> */</span><br><span class="line">@Data</span><br><span class="line">public class StudentEntity &#123;</span><br><span class="line">    //学生姓名</span><br><span class="line">    private String name;</span><br><span class="line">    //年龄</span><br><span class="line">    private String age;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>学生实体添加与页面参数对应的字段，名称、年龄。</p>
<h3 id="编写CustomerArgumentResolver参数装载"><a href="#编写CustomerArgumentResolver参数装载" class="headerlink" title="编写CustomerArgumentResolver参数装载"></a>编写CustomerArgumentResolver参数装载</h3><p>在写参数装载之前，我们需要先了解下它的接口<code>HandlerMethodArgumentResolver</code>，该接口内定义了两个方法：</p>
<h6 id="supportsParameter"><a href="#supportsParameter" class="headerlink" title="supportsParameter"></a>supportsParameter</h6><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">boolean supportsParameter(MethodParameter var1);</span><br></pre></td></tr></table></figure>
<p><code>supportsParameter</code>方法顾名思义，是允许装载的参数，也就是说方法返回<code>true</code>时才会指定装载方法完成参数装载。</p>
<h6 id="resolveArgument"><a href="#resolveArgument" class="headerlink" title="resolveArgument"></a>resolveArgument</h6><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">Object resolveArgument(MethodParameter var1, ModelAndViewContainer var2, NativeWebRequest var3, WebDataBinderFactory var4) throws Exception;</span><br></pre></td></tr></table></figure>
<p><code>resolveArgument</code>方法是参数状态的实现逻辑方法，该方法返回的值会直接装载到指定的参数上，有木有很神奇啊？下面我们就创建实现类来揭开这位神奇的姑娘的面纱吧！</p>
<p>创建<code>CustomerArgumentResolver</code>实现接口<code>HandlerMethodArgumentResolver</code>内的两个方法，具体实现代码如下所示：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br><span class="line">115</span><br><span class="line">116</span><br><span class="line">117</span><br><span class="line">118</span><br><span class="line">119</span><br><span class="line">120</span><br><span class="line">121</span><br><span class="line">122</span><br><span class="line">123</span><br><span class="line">124</span><br><span class="line">125</span><br><span class="line">126</span><br><span class="line">127</span><br><span class="line">128</span><br><span class="line">129</span><br><span class="line">130</span><br><span class="line">131</span><br><span class="line">132</span><br><span class="line">133</span><br><span class="line">134</span><br><span class="line">135</span><br><span class="line">136</span><br><span class="line">137</span><br><span class="line">138</span><br><span class="line">139</span><br><span class="line">140</span><br><span class="line">141</span><br><span class="line">142</span><br><span class="line">143</span><br><span class="line">144</span><br><span class="line">145</span><br><span class="line">146</span><br><span class="line">147</span><br><span class="line">148</span><br><span class="line">149</span><br><span class="line">150</span><br><span class="line">151</span><br><span class="line">152</span><br><span class="line">153</span><br><span class="line">154</span><br><span class="line">155</span><br><span class="line">156</span><br><span class="line">157</span><br><span class="line">158</span><br><span class="line">159</span><br><span class="line">160</span><br><span class="line">161</span><br><span class="line">162</span><br><span class="line">163</span><br><span class="line">164</span><br><span class="line">165</span><br><span class="line">166</span><br><span class="line">167</span><br><span class="line">168</span><br><span class="line">169</span><br><span class="line">170</span><br><span class="line">171</span><br><span class="line">172</span><br><span class="line">173</span><br><span class="line">174</span><br><span class="line">175</span><br><span class="line">176</span><br><span class="line">177</span><br><span class="line">178</span><br><span class="line">179</span><br><span class="line">180</span><br><span class="line">181</span><br><span class="line">182</span><br><span class="line">183</span><br><span class="line">184</span><br><span class="line">185</span><br><span class="line">186</span><br><span class="line">187</span><br><span class="line">188</span><br><span class="line">189</span><br><span class="line">190</span><br><span class="line">191</span><br><span class="line">192</span><br><span class="line">193</span><br><span class="line">194</span><br><span class="line">195</span><br><span class="line">196</span><br><span class="line">197</span><br><span class="line">198</span><br><span class="line">199</span><br><span class="line">200</span><br><span class="line">201</span><br><span class="line">202</span><br><span class="line">203</span><br><span class="line">204</span><br><span class="line">205</span><br><span class="line">206</span><br><span class="line">207</span><br><span class="line">208</span><br><span class="line">209</span><br><span class="line">210</span><br><span class="line">211</span><br><span class="line">212</span><br><span class="line">213</span><br><span class="line">214</span><br><span class="line">215</span><br><span class="line">216</span><br><span class="line">217</span><br><span class="line">218</span><br><span class="line">219</span><br><span class="line">220</span><br><span class="line">221</span><br><span class="line">222</span><br><span class="line">223</span><br><span class="line">224</span><br><span class="line">225</span><br><span class="line">226</span><br><span class="line">227</span><br><span class="line">228</span><br><span class="line">229</span><br><span class="line">230</span><br><span class="line">231</span><br><span class="line">232</span><br><span class="line">233</span><br><span class="line">234</span><br><span class="line">235</span><br><span class="line">236</span><br><span class="line">237</span><br><span class="line">238</span><br><span class="line">239</span><br><span class="line">240</span><br><span class="line">241</span><br><span class="line">242</span><br><span class="line">243</span><br><span class="line">244</span><br><span class="line">245</span><br><span class="line">246</span><br><span class="line">247</span><br><span class="line">248</span><br><span class="line">249</span><br><span class="line">250</span><br><span class="line">251</span><br><span class="line">252</span><br><span class="line">253</span><br><span class="line">254</span><br><span class="line">255</span><br><span class="line">256</span><br><span class="line">257</span><br><span class="line">258</span><br><span class="line">259</span><br><span class="line">260</span><br><span class="line">261</span><br><span class="line">262</span><br><span class="line">263</span><br><span class="line">264</span><br><span class="line">265</span><br><span class="line">266</span><br><span class="line">267</span><br><span class="line">268</span><br><span class="line">269</span><br><span class="line">270</span><br><span class="line">271</span><br><span class="line">272</span><br><span class="line">273</span><br><span class="line">274</span><br><span class="line">275</span><br><span class="line">276</span><br><span class="line">277</span><br><span class="line">278</span><br><span class="line">279</span><br><span class="line">280</span><br><span class="line">281</span><br><span class="line">282</span><br><span class="line">283</span><br><span class="line">284</span><br><span class="line">285</span><br><span class="line">286</span><br><span class="line">287</span><br><span class="line">288</span><br><span class="line">289</span><br><span class="line">290</span><br><span class="line">291</span><br><span class="line">292</span><br><span class="line">293</span><br><span class="line">294</span><br><span class="line">295</span><br><span class="line">296</span><br><span class="line">297</span><br><span class="line">298</span><br><span class="line">299</span><br><span class="line">300</span><br><span class="line">301</span><br><span class="line">302</span><br><span class="line">303</span><br><span class="line">304</span><br><span class="line">305</span><br><span class="line">306</span><br><span class="line">307</span><br><span class="line">308</span><br><span class="line">309</span><br><span class="line">310</span><br><span class="line">311</span><br><span class="line">312</span><br><span class="line">313</span><br><span class="line">314</span><br><span class="line">315</span><br><span class="line">316</span><br><span class="line">317</span><br><span class="line">318</span><br><span class="line">319</span><br><span class="line">320</span><br><span class="line">321</span><br><span class="line">322</span><br><span class="line">323</span><br><span class="line">324</span><br><span class="line">325</span><br><span class="line">326</span><br><span class="line">327</span><br><span class="line">328</span><br><span class="line">329</span><br><span class="line">330</span><br><span class="line">331</span><br><span class="line">332</span><br><span class="line">333</span><br><span class="line">334</span><br><span class="line">335</span><br><span class="line">336</span><br><span class="line">337</span><br><span class="line">338</span><br><span class="line">339</span><br><span class="line">340</span><br><span class="line">341</span><br><span class="line">342</span><br><span class="line">343</span><br><span class="line">344</span><br><span class="line">345</span><br><span class="line">346</span><br></pre></td><td class="code"><pre><span class="line">package com.yuqiyu.chapter36.resovler;</span><br><span class="line"></span><br><span class="line">import com.yuqiyu.chapter36.annotation.ParameterModel;</span><br><span class="line">import org.slf4j.Logger;</span><br><span class="line">import org.slf4j.LoggerFactory;</span><br><span class="line">import org.springframework.beans.BeanUtils;</span><br><span class="line">import org.springframework.core.MethodParameter;</span><br><span class="line">import org.springframework.core.convert.ConversionService;</span><br><span class="line">import org.springframework.core.convert.TypeDescriptor;</span><br><span class="line">import org.springframework.util.StringUtils;</span><br><span class="line">import org.springframework.validation.DataBinder;</span><br><span class="line">import org.springframework.web.bind.support.WebDataBinderFactory;</span><br><span class="line">import org.springframework.web.context.request.NativeWebRequest;</span><br><span class="line">import org.springframework.web.context.request.RequestAttributes;</span><br><span class="line">import org.springframework.web.method.support.HandlerMethodArgumentResolver;</span><br><span class="line">import org.springframework.web.method.support.ModelAndViewContainer;</span><br><span class="line">import org.springframework.web.servlet.HandlerMapping;</span><br><span class="line"></span><br><span class="line">import java.lang.reflect.Field;</span><br><span class="line">import java.util.*;</span><br><span class="line"></span><br><span class="line">/**</span><br><span class="line"> * 自定义参数装载</span><br><span class="line"> * ========================</span><br><span class="line"> * Created with IntelliJ IDEA.</span><br><span class="line"> * User：恒宇少年</span><br><span class="line"> * Date：2017/9/16</span><br><span class="line"> * Time：22:11</span><br><span class="line"> * 码云：http://git.oschina.net/jnyqy</span><br><span class="line"> * ========================</span><br><span class="line"> */</span><br><span class="line">public class CustomerArgumentResolver</span><br><span class="line">    implements HandlerMethodArgumentResolver</span><br><span class="line">&#123;</span><br><span class="line">    /**</span><br><span class="line">     * 日志对象</span><br><span class="line">     */</span><br><span class="line">    private Logger logger = LoggerFactory.getLogger(CustomerArgumentResolver.class);</span><br><span class="line">    /**</span><br><span class="line">     * 该方法返回true时调用resolveArgument方法执行逻辑</span><br><span class="line">     * spring家族的架构设计万变不离其宗啊，在之前event &amp; listener也是用到了同样的方式</span><br><span class="line">     * @param methodParameter</span><br><span class="line">     * @return</span><br><span class="line">     */</span><br><span class="line">    @Override</span><br><span class="line">    public boolean supportsParameter(MethodParameter methodParameter) &#123;</span><br><span class="line">        return methodParameter.hasParameterAnnotation(ParameterModel.class);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    /**</span><br><span class="line">     * 装载参数</span><br><span class="line">     * @param methodParameter 方法参数</span><br><span class="line">     * @param modelAndViewContainer 返回视图容器</span><br><span class="line">     * @param nativeWebRequest 本次请求对象</span><br><span class="line">     * @param webDataBinderFactory 数据绑定工厂</span><br><span class="line">     * @return</span><br><span class="line">     * @throws Exception</span><br><span class="line">     */</span><br><span class="line">    @Override</span><br><span class="line">    public Object resolveArgument (</span><br><span class="line">            MethodParameter methodParameter,</span><br><span class="line">            ModelAndViewContainer modelAndViewContainer,</span><br><span class="line">            NativeWebRequest nativeWebRequest,</span><br><span class="line">            WebDataBinderFactory webDataBinderFactory</span><br><span class="line">    )</span><br><span class="line">            throws Exception</span><br><span class="line">    &#123;</span><br><span class="line">        String parameterName = methodParameter.getParameterName();</span><br><span class="line">        logger.info(&quot;参数名称：&#123;&#125;&quot;,parameterName);</span><br><span class="line">        /**</span><br><span class="line">         * 目标返回对象</span><br><span class="line">         * 如果Model存在该Attribute时从module内获取并设置为返回值</span><br><span class="line">         * 如果Model不存在该Attribute则从request parameterMap内获取并设置为返回值</span><br><span class="line">         */</span><br><span class="line">        Object target = modelAndViewContainer.containsAttribute(parameterName) ?</span><br><span class="line">                modelAndViewContainer.getModel().get(parameterName) : createAttribute(parameterName, methodParameter, webDataBinderFactory, nativeWebRequest);;</span><br><span class="line"></span><br><span class="line">        /**</span><br><span class="line">         * 返回内容，这里返回的内容才是最终装载到参数的值</span><br><span class="line">         */</span><br><span class="line">        return target;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    /**</span><br><span class="line">     * 根据参数attributeName获取请求的值</span><br><span class="line">     * @param attributeName 请求参数</span><br><span class="line">     * @param parameter method 参数对象</span><br><span class="line">     * @param binderFactory 数据绑定工厂</span><br><span class="line">     * @param request 请求对象</span><br><span class="line">     * @return</span><br><span class="line">     * @throws Exception</span><br><span class="line">     */</span><br><span class="line">    protected Object createAttribute(String attributeName, MethodParameter parameter,</span><br><span class="line">                                     WebDataBinderFactory binderFactory, NativeWebRequest request) throws Exception &#123;</span><br><span class="line">        /**</span><br><span class="line">         * 获取attributeName的值</span><br><span class="line">         */</span><br><span class="line">        String value = getRequestValueForAttribute(attributeName, request);</span><br><span class="line"></span><br><span class="line">        /**</span><br><span class="line">         * 如果存在值</span><br><span class="line">         */</span><br><span class="line">        if (value != null) &#123;</span><br><span class="line">            /**</span><br><span class="line">             * 进行类型转换</span><br><span class="line">             * 检查请求的类型与目标参数类型是否可以进行转换</span><br><span class="line">             */</span><br><span class="line">            Object attribute = convertAttributeToParameterValue(value, attributeName, parameter, binderFactory, request);</span><br><span class="line">            /**</span><br><span class="line">             * 如果存在转换后的值，则返回</span><br><span class="line">             */</span><br><span class="line">            if (attribute != null) &#123;</span><br><span class="line">                return attribute;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">        /**</span><br><span class="line">         * 检查request parameterMap 内是否存在以attributeName作为前缀的数据</span><br><span class="line">         * 如果存在则根据字段的类型来进行设置值、集合、数组等</span><br><span class="line">         */</span><br><span class="line">        else</span><br><span class="line">        &#123;</span><br><span class="line">            Object attribute = putParameters(parameter,request);</span><br><span class="line">            if(attribute!=null)</span><br><span class="line">            &#123;</span><br><span class="line">                return attribute;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">        /**</span><br><span class="line">         * 如果以上两种条件不符合，直接返回初始化参数类型的空对象</span><br><span class="line">         */</span><br><span class="line">        return BeanUtils.instantiateClass(parameter.getParameterType());</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    /**</span><br><span class="line">     * 将attribute的值转换为parameter参数值类型</span><br><span class="line">     * @param sourceValue 源请求值</span><br><span class="line">     * @param attributeName 参数名</span><br><span class="line">     * @param parameter 目标参数对象</span><br><span class="line">     * @param binderFactory 数据绑定工厂</span><br><span class="line">     * @param request 请求对象</span><br><span class="line">     * @return</span><br><span class="line">     * @throws Exception</span><br><span class="line">     */</span><br><span class="line">    protected Object convertAttributeToParameterValue(String sourceValue,</span><br><span class="line">                                                     String attributeName,</span><br><span class="line">                                                     MethodParameter parameter,</span><br><span class="line">                                                     WebDataBinderFactory binderFactory,</span><br><span class="line">                                                     NativeWebRequest request) throws Exception &#123;</span><br><span class="line">        /**</span><br><span class="line">         * 获取类型转换业务逻辑实现类</span><br><span class="line">         */</span><br><span class="line">        DataBinder binder = binderFactory.createBinder(request, null, attributeName);</span><br><span class="line">        ConversionService conversionService = binder.getConversionService();</span><br><span class="line">        if (conversionService != null) &#123;</span><br><span class="line">            /**</span><br><span class="line">             * 源类型描述</span><br><span class="line">             */</span><br><span class="line">            TypeDescriptor source = TypeDescriptor.valueOf(String.class);</span><br><span class="line">            /**</span><br><span class="line">             * 根据目标参数对象获取目标参数类型描述</span><br><span class="line">             */</span><br><span class="line">            TypeDescriptor target = new TypeDescriptor(parameter);</span><br><span class="line">            /**</span><br><span class="line">             * 验证是否可以进行转换</span><br><span class="line">             */</span><br><span class="line">            if (conversionService.canConvert(source, target)) &#123;</span><br><span class="line">                /**</span><br><span class="line">                 * 返回转换后的值</span><br><span class="line">                 */</span><br><span class="line">                return binder.convertIfNecessary(sourceValue, parameter.getParameterType(), parameter);</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">        return null;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    /**</span><br><span class="line">     * 从request parameterMap集合内获取attributeName的值</span><br><span class="line">     * @param attributeName 参数名称</span><br><span class="line">     * @param request 请求对象</span><br><span class="line">     * @return</span><br><span class="line">     */</span><br><span class="line">    protected String getRequestValueForAttribute(String attributeName, NativeWebRequest request) &#123;</span><br><span class="line">        /**</span><br><span class="line">         * 获取PathVariables参数集合</span><br><span class="line">         */</span><br><span class="line">        Map&lt;String, String&gt; variables = getUriTemplateVariables(request);</span><br><span class="line">        /**</span><br><span class="line">         * 如果PathVariables参数集合内存在该attributeName</span><br><span class="line">         * 直接返回相对应的值</span><br><span class="line">         */</span><br><span class="line">        if (StringUtils.hasText(variables.get(attributeName))) &#123;</span><br><span class="line">            return variables.get(attributeName);</span><br><span class="line">        &#125;</span><br><span class="line">        /**</span><br><span class="line">         * 如果request parameterMap内存在该attributeName</span><br><span class="line">         * 直接返回相对应的值</span><br><span class="line">         */</span><br><span class="line">        else if (StringUtils.hasText(request.getParameter(attributeName))) &#123;</span><br><span class="line">            return request.getParameter(attributeName);</span><br><span class="line">        &#125;</span><br><span class="line">        //不存在时返回null</span><br><span class="line">        else &#123;</span><br><span class="line">            return null;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    /**</span><br><span class="line">     * 获取指定前缀的参数：包括uri varaibles 和 parameters</span><br><span class="line">     *</span><br><span class="line">     * @param namePrefix</span><br><span class="line">     * @param request</span><br><span class="line">     * @return</span><br><span class="line">     * @subPrefix 是否截取掉namePrefix的前缀</span><br><span class="line">     */</span><br><span class="line">    protected Map&lt;String, String[]&gt; getPrefixParameterMap(String namePrefix, NativeWebRequest request, boolean subPrefix) &#123;</span><br><span class="line">        Map&lt;String, String[]&gt; result = new HashMap();</span><br><span class="line">        /**</span><br><span class="line">         * 从PathVariables内获取该前缀的参数列表</span><br><span class="line">         */</span><br><span class="line">        Map&lt;String, String&gt; variables = getUriTemplateVariables(request);</span><br><span class="line"></span><br><span class="line">        int namePrefixLength = namePrefix.length();</span><br><span class="line">        for (String name : variables.keySet()) &#123;</span><br><span class="line">            if (name.startsWith(namePrefix)) &#123;</span><br><span class="line"></span><br><span class="line">                //page.pn  则截取 pn</span><br><span class="line">                if (subPrefix) &#123;</span><br><span class="line">                    char ch = name.charAt(namePrefix.length());</span><br><span class="line">                    //如果下一个字符不是 数字 . _  则不可能是查询 只是前缀类似</span><br><span class="line">                    if (illegalChar(ch)) &#123;</span><br><span class="line">                        continue;</span><br><span class="line">                    &#125;</span><br><span class="line">                    result.put(name.substring(namePrefixLength + 1), new String[]&#123;variables.get(name)&#125;);</span><br><span class="line">                &#125; else &#123;</span><br><span class="line">                    result.put(name, new String[]&#123;variables.get(name)&#125;);</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        /**</span><br><span class="line">         * 从request parameterMap集合内获取该前缀的参数列表</span><br><span class="line">         */</span><br><span class="line">        Iterator&lt;String&gt; parameterNames = request.getParameterNames();</span><br><span class="line">        while (parameterNames.hasNext()) &#123;</span><br><span class="line">            String name = parameterNames.next();</span><br><span class="line">            if (name.startsWith(namePrefix)) &#123;</span><br><span class="line">                //page.pn  则截取 pn</span><br><span class="line">                if (subPrefix) &#123;</span><br><span class="line">                    char ch = name.charAt(namePrefix.length());</span><br><span class="line">                    //如果下一个字符不是 数字 . _  则不可能是查询 只是前缀类似</span><br><span class="line">                    if (illegalChar(ch)) &#123;</span><br><span class="line">                        continue;</span><br><span class="line">                    &#125;</span><br><span class="line">                    result.put(name.substring(namePrefixLength + 1), request.getParameterValues(name));</span><br><span class="line">                &#125; else &#123;</span><br><span class="line">                    result.put(name, request.getParameterValues(name));</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        return result;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    /**</span><br><span class="line">     * 验证参数前缀是否合法</span><br><span class="line">     * @param ch</span><br><span class="line">     * @return</span><br><span class="line">     */</span><br><span class="line">    private boolean illegalChar(char ch) &#123;</span><br><span class="line">        return ch != &apos;.&apos; &amp;&amp; ch != &apos;_&apos; &amp;&amp; !(ch &gt;= &apos;0&apos; &amp;&amp; ch &lt;= &apos;9&apos;);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    /**</span><br><span class="line">     * 获取PathVariables集合</span><br><span class="line">     * @param request 请求对象</span><br><span class="line">     * @return</span><br><span class="line">     */</span><br><span class="line">    protected final Map&lt;String, String&gt; getUriTemplateVariables(NativeWebRequest request) &#123;</span><br><span class="line">        Map&lt;String, String&gt; variables =</span><br><span class="line">                (Map&lt;String, String&gt;) request.getAttribute(</span><br><span class="line">                        HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE, RequestAttributes.SCOPE_REQUEST);</span><br><span class="line">        return (variables != null) ? variables : Collections.emptyMap();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    /**</span><br><span class="line">     * 从request内获取parameter前缀的所有参数</span><br><span class="line">     * 并根据parameter的类型将对应字段的值设置到parmaeter对象内并返回</span><br><span class="line">     * @param parameter</span><br><span class="line">     * @param request</span><br><span class="line">     * @return</span><br><span class="line">     */</span><br><span class="line">    protected Object putParameters(MethodParameter parameter,NativeWebRequest request)</span><br><span class="line">    &#123;</span><br><span class="line">        /**</span><br><span class="line">         * 根据请求参数类型初始化空对象</span><br><span class="line">         */</span><br><span class="line">        Object object = BeanUtils.instantiateClass(parameter.getParameterType());</span><br><span class="line">        /**</span><br><span class="line">         * 获取指定前缀的请求参数集合</span><br><span class="line">         */</span><br><span class="line">        Map&lt;String, String[]&gt; parameters = getPrefixParameterMap(parameter.getParameterName(),request,true);</span><br><span class="line">        Iterator&lt;String&gt; iterator = parameters.keySet().iterator();</span><br><span class="line">        while(iterator.hasNext())</span><br><span class="line">        &#123;</span><br><span class="line">            //字段名称</span><br><span class="line">            String fieldName = iterator.next();</span><br><span class="line">            //请求参数值</span><br><span class="line">            String[] parameterValue = parameters.get(fieldName);</span><br><span class="line">            try &#123;</span><br><span class="line">                Field field = object.getClass().getDeclaredField(fieldName);</span><br><span class="line">                field.setAccessible(true);</span><br><span class="line"></span><br><span class="line">                //字段的类型</span><br><span class="line">                Class&lt;?&gt; fieldTargetType = field.getType();</span><br><span class="line"></span><br><span class="line">                /**</span><br><span class="line">                 * List（ArrayList、LinkedList）类型</span><br><span class="line">                 * 将数组类型的值转换为List集合对象</span><br><span class="line">                 */</span><br><span class="line">                if(List.class.isAssignableFrom(fieldTargetType))</span><br><span class="line">                &#123;</span><br><span class="line">                    field.set(object, Arrays.asList(parameterValue));</span><br><span class="line">                &#125;</span><br><span class="line">                /**</span><br><span class="line">                 *Object数组类型，直接将数组值设置为目标字段的值</span><br><span class="line">                 */</span><br><span class="line">                else if(Object[].class.isAssignableFrom(fieldTargetType))</span><br><span class="line">                &#123;</span><br><span class="line">                    field.set(object, parameterValue);</span><br><span class="line">                &#125;</span><br><span class="line">                /**</span><br><span class="line">                 * 单值时获取数组索引为0的值</span><br><span class="line">                 */</span><br><span class="line">                else &#123;</span><br><span class="line">                    field.set(object, parameterValue[0]);</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line">            catch (Exception e)</span><br><span class="line">            &#123;</span><br><span class="line">                logger.error(&quot;Set Field：&#123;&#125; Value Error，In &#123;&#125;&quot;,fieldName,object.getClass().getName());</span><br><span class="line">                continue;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">        return object;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<blockquote>
<p>上面我直接贴出了参数装载的全部实现方法，下面我们就开始按照装载的流程进行讲解。</p>
<h5 id="supportsParameter方法实现"><a href="#supportsParameter方法实现" class="headerlink" title="supportsParameter方法实现"></a>supportsParameter方法实现</h5><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">/**</span><br><span class="line">    * 该方法返回true时调用resolveArgument方法执行逻辑</span><br><span class="line">    * spring家族的架构设计万变不离其宗啊，在之前event &amp; listener也是用到了同样的方式</span><br><span class="line">    * @param methodParameter</span><br><span class="line">    * @return</span><br><span class="line">    */</span><br><span class="line">   @Override</span><br><span class="line">   public boolean supportsParameter(MethodParameter methodParameter) &#123;</span><br><span class="line">       return methodParameter.hasParameterAnnotation(ParameterModel.class);</span><br><span class="line">   &#125;</span><br></pre></td></tr></table></figure>
</blockquote>
<p>我们只对配置了<code>ParameterModel</code>注解的参数进行装载。</p>
<h5 id="resolveArgument方法实现"><a href="#resolveArgument方法实现" class="headerlink" title="resolveArgument方法实现"></a>resolveArgument方法实现</h5><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br></pre></td><td class="code"><pre><span class="line">/**</span><br><span class="line">    * 装载参数</span><br><span class="line">    * @param methodParameter 方法参数</span><br><span class="line">    * @param modelAndViewContainer 返回视图容器</span><br><span class="line">    * @param nativeWebRequest 本次请求对象</span><br><span class="line">    * @param webDataBinderFactory 数据绑定工厂</span><br><span class="line">    * @return</span><br><span class="line">    * @throws Exception</span><br><span class="line">    */</span><br><span class="line">   @Override</span><br><span class="line">   public Object resolveArgument (</span><br><span class="line">           MethodParameter methodParameter,</span><br><span class="line">           ModelAndViewContainer modelAndViewContainer,</span><br><span class="line">           NativeWebRequest nativeWebRequest,</span><br><span class="line">           WebDataBinderFactory webDataBinderFactory</span><br><span class="line">   )</span><br><span class="line">           throws Exception</span><br><span class="line">   &#123;</span><br><span class="line">       String parameterName = methodParameter.getParameterName();</span><br><span class="line">       logger.info(&quot;参数名称：&#123;&#125;&quot;,parameterName);</span><br><span class="line">       /**</span><br><span class="line">        * 目标返回对象</span><br><span class="line">        * 如果Model存在该Attribute时从module内获取并设置为返回值</span><br><span class="line">        * 如果Model不存在该Attribute则从request parameterMap内获取并设置为返回值</span><br><span class="line">        */</span><br><span class="line">       Object target = modelAndViewContainer.containsAttribute(parameterName) ?</span><br><span class="line">               modelAndViewContainer.getModel().get(parameterName) : createAttribute(parameterName, methodParameter, webDataBinderFactory, nativeWebRequest);;</span><br><span class="line"></span><br><span class="line">       /**</span><br><span class="line">        * 返回内容，这里返回的内容才是最终装载到参数的值</span><br><span class="line">        */</span><br><span class="line">       return target;</span><br><span class="line">   &#125;</span><br></pre></td></tr></table></figure>
<p>该方法作为装载参数逻辑的入口，我们从<code>MethodParameter</code>对象内获取了参数的名称，根据该名称检查Model内是否存在该名称的值，如果存在则直接使用并返回，反则需要从<code>ParameterMap</code>内获取对应该参数名称的值返回。<br>我们下面主要看看从<code>parameterMap</code>获取的方法实现</p>
<h5 id="createAttribute方法实现"><a href="#createAttribute方法实现" class="headerlink" title="createAttribute方法实现"></a>createAttribute方法实现</h5><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br></pre></td><td class="code"><pre><span class="line">/**</span><br><span class="line">     * 根据参数attributeName获取请求的值</span><br><span class="line">     * @param attributeName 请求参数</span><br><span class="line">     * @param parameter method 参数对象</span><br><span class="line">     * @param binderFactory 数据绑定工厂</span><br><span class="line">     * @param request 请求对象</span><br><span class="line">     * @return</span><br><span class="line">     * @throws Exception</span><br><span class="line">     */</span><br><span class="line">    protected Object createAttribute(String attributeName, MethodParameter parameter,</span><br><span class="line">                                     WebDataBinderFactory binderFactory, NativeWebRequest request) throws Exception &#123;</span><br><span class="line">        /**</span><br><span class="line">         * 获取attributeName的值</span><br><span class="line">         */</span><br><span class="line">        String value = getRequestValueForAttribute(attributeName, request);</span><br><span class="line"></span><br><span class="line">        /**</span><br><span class="line">         * 如果存在值</span><br><span class="line">         */</span><br><span class="line">        if (value != null) &#123;</span><br><span class="line">            /**</span><br><span class="line">             * 进行类型转换</span><br><span class="line">             * 检查请求的类型与目标参数类型是否可以进行转换</span><br><span class="line">             */</span><br><span class="line">            Object attribute = convertAttributeToParameterValue(value, attributeName, parameter, binderFactory, request);</span><br><span class="line">            /**</span><br><span class="line">             * 如果存在转换后的值，则返回</span><br><span class="line">             */</span><br><span class="line">            if (attribute != null) &#123;</span><br><span class="line">                return attribute;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">        /**</span><br><span class="line">         * 检查request parameterMap 内是否存在以attributeName作为前缀的数据</span><br><span class="line">         * 如果存在则根据字段的类型来进行设置值、集合、数组等</span><br><span class="line">         */</span><br><span class="line">        else</span><br><span class="line">        &#123;</span><br><span class="line">            Object attribute = putParameters(parameter,request);</span><br><span class="line">            if(attribute!=null)</span><br><span class="line">            &#123;</span><br><span class="line">                return attribute;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">        /**</span><br><span class="line">         * 如果以上两种条件不符合，直接返回初始化参数类型的空对象</span><br><span class="line">         */</span><br><span class="line">        return BeanUtils.instantiateClass(parameter.getParameterType());</span><br><span class="line">    &#125;</span><br></pre></td></tr></table></figure>
<p>该方法的逻辑存在两个分支，首先通过调用<code>getRequestValueForAttribute</code>方法从<code>parameterMap</code>内获取指定属性名的请求值，如果存在值则需要验证是否可以完成类型转换，验证通过后则直接返回值。</p>
<p>上面的部分其实是<code>SpringMVC</code>原有的参数装载的流程，下面我们就来根据需求个性化定制装载逻辑。</p>
<h5 id="putParameters方法实现"><a href="#putParameters方法实现" class="headerlink" title="putParameters方法实现"></a>putParameters方法实现</h5><p>该方法实现了自定义规则<code>xxx.xxx</code>方式进行参数装载的逻辑，我们在前台传递参数的时候只需要将<code>Controller</code>内方法参数名称作为传递的前缀即可，如：<code>teacher.name</code>、<code>student.name</code>。<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br></pre></td><td class="code"><pre><span class="line">/**</span><br><span class="line">     * 从request内获取parameter前缀的所有参数</span><br><span class="line">     * 并根据parameter的类型将对应字段的值设置到parmaeter对象内并返回</span><br><span class="line">     * @param parameter</span><br><span class="line">     * @param request</span><br><span class="line">     * @return</span><br><span class="line">     */</span><br><span class="line">    protected Object putParameters(MethodParameter parameter,NativeWebRequest request)</span><br><span class="line">    &#123;</span><br><span class="line">        /**</span><br><span class="line">         * 根据请求参数类型初始化空对象</span><br><span class="line">         */</span><br><span class="line">        Object object = BeanUtils.instantiateClass(parameter.getParameterType());</span><br><span class="line">        /**</span><br><span class="line">         * 获取指定前缀的请求参数集合</span><br><span class="line">         */</span><br><span class="line">        Map&lt;String, String[]&gt; parameters = getPrefixParameterMap(parameter.getParameterName(),request,true);</span><br><span class="line">        Iterator&lt;String&gt; iterator = parameters.keySet().iterator();</span><br><span class="line">        while(iterator.hasNext())</span><br><span class="line">        &#123;</span><br><span class="line">            //字段名称</span><br><span class="line">            String fieldName = iterator.next();</span><br><span class="line">            //请求参数值</span><br><span class="line">            String[] parameterValue = parameters.get(fieldName);</span><br><span class="line">            try &#123;</span><br><span class="line">                Field field = object.getClass().getDeclaredField(fieldName);</span><br><span class="line">                field.setAccessible(true);</span><br><span class="line"></span><br><span class="line">                //字段的类型</span><br><span class="line">                Class&lt;?&gt; fieldTargetType = field.getType();</span><br><span class="line"></span><br><span class="line">                /**</span><br><span class="line">                 * List（ArrayList、LinkedList）类型</span><br><span class="line">                 * 将数组类型的值转换为List集合对象</span><br><span class="line">                 */</span><br><span class="line">                if(List.class.isAssignableFrom(fieldTargetType))</span><br><span class="line">                &#123;</span><br><span class="line">                    field.set(object, Arrays.asList(parameterValue));</span><br><span class="line">                &#125;</span><br><span class="line">                /**</span><br><span class="line">                 *Object数组类型，直接将数组值设置为目标字段的值</span><br><span class="line">                 */</span><br><span class="line">                else if(Object[].class.isAssignableFrom(fieldTargetType))</span><br><span class="line">                &#123;</span><br><span class="line">                    field.set(object, parameterValue);</span><br><span class="line">                &#125;</span><br><span class="line">                /**</span><br><span class="line">                 * 单值时获取数组索引为0的值</span><br><span class="line">                 */</span><br><span class="line">                else &#123;</span><br><span class="line">                    field.set(object, parameterValue[0]);</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line">            catch (Exception e)</span><br><span class="line">            &#123;</span><br><span class="line">                logger.error(&quot;Set Field：&#123;&#125; Value Error，In &#123;&#125;&quot;,fieldName,object.getClass().getName());</span><br><span class="line">                continue;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">        return object;</span><br><span class="line">    &#125;</span><br></pre></td></tr></table></figure></p>
<p>该方法首先实例化了一个<code>MethodParameter</code>类型的<code>空对象</code>，然后通过<code>getPrefixParameterMap</code>获取<code>PathVariables</code>、<code>ParameterMap</code>内前缀为<code>MethodParameter</code>名称的请求参数列表，遍历列表对应设置<br><code>object</code>内的字段，用于完成参数的装载，在装载过程中，我这里分别根据<code>Collection</code>、<code>List</code>、<code>Array</code>、<code>Single</code>类型进行了处理（注意：这里需要根据项目需求进行调整装载类型）。</p>
<h3 id="配置Spring托管CustomerArgumentResolver"><a href="#配置Spring托管CustomerArgumentResolver" class="headerlink" title="配置Spring托管CustomerArgumentResolver"></a>配置Spring托管CustomerArgumentResolver</h3><p>我们将<code>CustomerArgumentResolver</code>托管交付给<code>Spring</code>框架，我们来创建一个名叫<code>WebMvcConfiguration</code>的配置类，该类继承抽象类<code>WebMvcConfigurerAdapter</code>，代码如下所示：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br></pre></td><td class="code"><pre><span class="line">/**</span><br><span class="line"> * springmvc 注解式配置类</span><br><span class="line"> * ========================</span><br><span class="line"> * Created with IntelliJ IDEA.</span><br><span class="line"> * User：恒宇少年</span><br><span class="line"> * Date：2017/9/16</span><br><span class="line"> * Time：22:15</span><br><span class="line"> * 码云：http://git.oschina.net/jnyqy</span><br><span class="line"> * ========================</span><br><span class="line"> */</span><br><span class="line">@Configuration</span><br><span class="line">public class WebMvcConfiguration</span><br><span class="line">    extends WebMvcConfigurerAdapter</span><br><span class="line">&#123;</span><br><span class="line">    /**</span><br><span class="line">     * 添加参数装载</span><br><span class="line">     * @param argumentResolvers</span><br><span class="line">     */</span><br><span class="line">    @Override</span><br><span class="line">    public void addArgumentResolvers(List&lt;HandlerMethodArgumentResolver&gt; argumentResolvers) &#123;</span><br><span class="line">        /**</span><br><span class="line">         * 将自定义的参数装载添加到spring内托管</span><br><span class="line">         */</span><br><span class="line">        argumentResolvers.add(new CustomerArgumentResolver());</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    /**</span><br><span class="line">     * 配置静态请求视图映射</span><br><span class="line">     * @param registry</span><br><span class="line">     */</span><br><span class="line">    @Override</span><br><span class="line">    public void addViewControllers(ViewControllerRegistry registry) &#123;</span><br><span class="line">        registry.addViewController(&quot;/index&quot;).setViewName(&quot;index&quot;);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>我们重写了<code>WebMvcConfigurerAdapter</code>抽象类内的两个方法<code>addArgumentResolvers</code>、<code>addViewControllers</code>，其中<code>addArgumentResolvers</code>方法完成了参数装载的托管。</p>
<p><code>addViewControllers</code>配置了视图控制器映射，这样我们访问<code>/index</code>地址就可以请求到<code>index.jsp</code>页面。</p>
<h3 id="创建测试控制器"><a href="#创建测试控制器" class="headerlink" title="创建测试控制器"></a>创建测试控制器</h3><p>创建名为<code>IndexController</code>的控制器并添加数据提交的方法，具体代码如下所示：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line">/**</span><br><span class="line"> * 表单提交控制器</span><br><span class="line"> * ========================</span><br><span class="line"> * Created with IntelliJ IDEA.</span><br><span class="line"> * User：恒宇少年</span><br><span class="line"> * Date：2017/9/16</span><br><span class="line"> * Time：22:26</span><br><span class="line"> * 码云：http://git.oschina.net/jnyqy</span><br><span class="line"> * ========================</span><br><span class="line"> */</span><br><span class="line">@RestController</span><br><span class="line">public class IndexController</span><br><span class="line">&#123;</span><br><span class="line">    /**</span><br><span class="line">     * 装载参数测试</span><br><span class="line">     * @return</span><br><span class="line">     */</span><br><span class="line">    @RequestMapping(value = &quot;/submit&quot;)</span><br><span class="line">    public String resolver(@ParameterModel TeacherEntity teacher, @ParameterModel StudentEntity student)</span><br><span class="line">    &#123;</span><br><span class="line">        return &quot;教师名称：&quot;+ JSON.toJSON(teacher.getName()) +&quot;，学生名称：&quot;+student.getName()+&quot;，学生年龄：&quot;+student.getAge();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>可以看到我们为<code>TeacherEntity</code>、<code>StudentEntity</code>分别添加了注解<code>@ParameterModel</code>，也就证明了这两个实体需要使用我们的<code>CustomerArgumentResolver</code>完成参数装载。</p>
<h1 id="运行测试"><a href="#运行测试" class="headerlink" title="运行测试"></a>运行测试</h1><p>在运行测试之前，我们需要修改下<code>index.jsp</code>内的参数映射前缀，修改后代码如下所示：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">&lt;form method=&quot;post&quot; action=&quot;/submit&quot;&gt;</span><br><span class="line">        教师姓名：&lt;input type=&quot;text&quot; name=&quot;teacher.name&quot;/&gt;&lt;br/&gt;&lt;br/&gt;</span><br><span class="line">        学生姓名：&lt;input type=&quot;text&quot; name=&quot;student.name&quot;/&gt;&lt;br/&gt;&lt;br/&gt;</span><br><span class="line">        学生年龄：&lt;input type=&quot;text&quot; name=&quot;student.age&quot;/&gt;&lt;br/&gt;&lt;br/&gt;</span><br><span class="line">        &lt;input type=&quot;submit&quot;/&gt;</span><br><span class="line">    &lt;/form&gt;</span><br></pre></td></tr></table></figure></p>
<h4 id="测试单值装载"><a href="#测试单值装载" class="headerlink" title="测试单值装载"></a>测试单值装载</h4><p>我们为教师名称、学生名称、学生年龄都分别添加了前缀，下面我们来启动项目，访问项目根下路径<code>/index</code>，如下图1所示：</p>
<p><img src="http://upload-images.jianshu.io/upload_images/4461954-e0f9d7cfc6f94af7.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="图1"><br>在上图1中输入了部分请求参数，点击“提交”按钮查看界面输出的效果，图下所示：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">教师名称：王老师，学生名称：张小跑，学生年龄：23</span><br></pre></td></tr></table></figure></p>
<p>可以看到参数已经被正确的装载到了不同的实体类内。</p>
<blockquote>
<p>上面的例子只是针对实体内的单个值的装载，下面我们来测试下<code>List</code>类型的值是否可以装载？</p>
</blockquote>
<h4 id="测试List装载"><a href="#测试List装载" class="headerlink" title="测试List装载"></a>测试List装载</h4><p>我们先来修改下教师实体内的名称为List，字段名称不需要变动，如下所示：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">//教师姓名</span><br><span class="line">private List&lt;String&gt; name;</span><br></pre></td></tr></table></figure></p>
<p>再来修改下<code>index.jsp</code>输入框，如下所示：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">&lt;form method=&quot;post&quot; action=&quot;/submit&quot;&gt;</span><br><span class="line">    语文老师姓名：&lt;input type=&quot;text&quot; name=&quot;teacher.name&quot;/&gt;&lt;br/&gt;&lt;br/&gt;</span><br><span class="line">    数学教师姓名：&lt;input type=&quot;text&quot; name=&quot;teacher.name&quot;/&gt;&lt;br/&gt;&lt;br/&gt;</span><br><span class="line">    学生姓名：&lt;input type=&quot;text&quot; name=&quot;student.name&quot;/&gt;&lt;br/&gt;&lt;br/&gt;</span><br><span class="line">    学生年龄：&lt;input type=&quot;text&quot; name=&quot;student.age&quot;/&gt;&lt;br/&gt;&lt;br/&gt;</span><br><span class="line">    &lt;input type=&quot;submit&quot;/&gt;</span><br><span class="line">&lt;/form&gt;</span><br></pre></td></tr></table></figure></p>
<p>在上代码中我们添加了两位老师的名称，接下来重启项目，再次提交测试，查看是不是我们想要的效果？<br>修改后的界面如下图2所示：</p>
<p><img src="http://upload-images.jianshu.io/upload_images/4461954-1cf288b1ed524fd9.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="图2"></p>
<p>界面输出内容如下所示：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">教师名称：[&quot;王老师&quot;,&quot;李老师&quot;]，学生名称：张小跑，学生年龄：24</span><br></pre></td></tr></table></figure></p>
<p>可以看到我们已经拿到了两位老师的名称，这也证明了我们的<code>CustomerArgumentResolver</code>是可以完成<code>List</code>的映射装载的。</p>
<h1 id="总结"><a href="#总结" class="headerlink" title="总结"></a>总结</h1><p>以上内容就是本章的全部讲解内容，本章简单实现了参数的状态，其中还有很多细节性质的逻辑，如：<code>@Valid</code>注解的生效、文件的上传等。在下一章我们会降到如果通过参数装载实现接口服务的安全认证。</p>
<p>本章代码已经上传到码云：<br>SpringBoot配套源码地址：<a href="https://gitee.com/hengboy/spring-boot-chapter" target="_blank" rel="noopener">https://gitee.com/hengboy/spring-boot-chapter</a><br>SpringCloud配套源码地址：<a href="https://gitee.com/hengboy/spring-cloud-chapter" target="_blank" rel="noopener">https://gitee.com/hengboy/spring-cloud-chapter</a><br>SpringBoot相关系列文章请访问：<a href="http://www.jianshu.com/p/9a08417e4e84" target="_blank" rel="noopener">目录：SpringBoot学习目录</a><br>QueryDSL相关系列文章请访问：<a href="http://www.jianshu.com/p/99a5ec5c3bd5" target="_blank" rel="noopener">QueryDSL通用查询框架学习目录</a><br>SpringDataJPA相关系列文章请访问：<a href="http://www.jianshu.com/p/615ed9c1fe84" target="_blank" rel="noopener">目录：SpringDataJPA学习目录</a><br>感谢阅读！<br>欢迎加入QQ技术交流群，共同进步。<br><img src="http://upload-images.jianshu.io/upload_images/4461954-f1d4cb64234b160a.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="QQ技术交流群"></p>

        
        </div>
        <footer class="article-footer">
            <div class="share-container">


    <div class="bdsharebuttonbox">
    <a href="#" class="bds_more" data-cmd="more">分享到：</a>
    <a href="#" class="bds_qzone" data-cmd="qzone" title="分享到QQ空间">QQ空间</a>
    <a href="#" class="bds_tsina" data-cmd="tsina" title="分享到新浪微博">新浪微博</a>
    <a href="#" class="bds_tqq" data-cmd="tqq" title="分享到腾讯微博">腾讯微博</a>
    <a href="#" class="bds_renren" data-cmd="renren" title="分享到人人网">人人网</a>
    <a href="#" class="bds_weixin" data-cmd="weixin" title="分享到微信">微信</a>
</div>
<script>
window._bd_share_config={"common":{"bdSnsKey":{},"bdText":"","bdMini":"2","bdMiniList":false,"bdPic":"","bdStyle":"0","bdSize":"16"},"share":{"bdSize":16}};with(document)0[(getElementsByTagName('head')[0]||body).appendChild(createElement('script')).src='http://bdimg.share.baidu.com/static/api/js/share.js?v=89860593.js?cdnversion='+~(-new Date()/36e5)];
</script>
<style>
    .bdshare_popup_box {
        border-radius: 4px;
        border: #e1e1e1 solid 1px;
    }
    .bdshare-button-style0-16 a,
    .bdshare-button-style0-16 .bds_more {
        padding-left: 20px;
        margin: 6px 10px 6px 0;
    }
    .bdshare_dialog_list a,
    .bdshare_popup_list a,
    .bdshare_popup_bottom a {
        font-family: 'Microsoft Yahei';
    }
    .bdshare_popup_top {
        display: none;
    }
    .bdshare_popup_bottom {
        height: auto;
        padding: 5px;
    }
</style>


</div>

            
    

        </footer>
    </div>
    
        
<nav id="article-nav">
    
        <a href="/spring-boot-chapter-37/" id="article-nav-newer" class="article-nav-link-wrap">
            <strong class="article-nav-caption">上一篇</strong>
            <div class="article-nav-title">
                
                    第三十七章：基于SpringBoot架构以及参数装载完成接口安全认证
                
            </div>
        </a>
    
    
        <a href="/spring-boot-chapter-35/" id="article-nav-older" class="article-nav-link-wrap">
            <strong class="article-nav-caption">下一篇</strong>
            <div class="article-nav-title">第三十五章：SpringBoot与单元测试的小秘密</div>
        </a>
    
</nav>


    
</article>


    
    

</section>
            
			
				
<aside id="sidebar">
   
        
    <div class="widget-wrap">
        <h3 class="widget-title">最新文章</h3>
        <div class="widget">
            <ul id="recent-post" class="no-thumbnail">
                
                    <li>
                        
                        <div class="item-inner">
                            <p class="item-category"><a class="article-category-link" href="/categories/SpringBoot-核心技术/">SpringBoot 核心技术</a></p>
                            <p class="item-title"><a href="/spring-boot-chapter-52/" class="title">第五十二章：基于SpringBoot2使用Rest访问MongoDB数据</a></p>
                            <p class="item-date"><time datetime="2018-04-21T16:00:00.000Z" itemprop="datePublished">2018-04-22</time></p>
                        </div>
                    </li>
                
                    <li>
                        
                        <div class="item-inner">
                            <p class="item-category"><a class="article-category-link" href="/categories/SpringBoot-核心技术/">SpringBoot 核心技术</a></p>
                            <p class="item-title"><a href="/spring-boot-chapter-51/" class="title">第五十一章：基于SpringBoot2 &amp; MongoDB完成自动化集成</a></p>
                            <p class="item-date"><time datetime="2018-04-15T16:00:00.000Z" itemprop="datePublished">2018-04-16</time></p>
                        </div>
                    </li>
                
                    <li>
                        
                        <div class="item-inner">
                            <p class="item-category"><a class="article-category-link" href="/categories/SpringBoot-核心技术/">SpringBoot 核心技术</a></p>
                            <p class="item-title"><a href="/spring-boot-chapter-50/" class="title">第五十章：SpringBoot2.0新特性 - 岂止至今最简单redis缓存集成</a></p>
                            <p class="item-date"><time datetime="2018-04-14T16:00:00.000Z" itemprop="datePublished">2018-04-15</time></p>
                        </div>
                    </li>
                
                    <li>
                        
                        <div class="item-inner">
                            <p class="item-category"><a class="article-category-link" href="/categories/SpringBoot-核心技术/">SpringBoot 核心技术</a></p>
                            <p class="item-title"><a href="/spring-boot-chapter-49/" class="title">第四十九章：SpringBoot2.0新特性 - 你get到WebMvcConfigurer两种配置方式了吗？</a></p>
                            <p class="item-date"><time datetime="2018-03-16T16:00:00.000Z" itemprop="datePublished">2018-03-17</time></p>
                        </div>
                    </li>
                
                    <li>
                        
                        <div class="item-inner">
                            <p class="item-category"><a class="article-category-link" href="/categories/SpringBoot-核心技术/">SpringBoot 核心技术</a></p>
                            <p class="item-title"><a href="/spring-boot-chapter-48/" class="title">第四十八章：SpringBoot2.0新特性 - RabbitMQ信任package设置</a></p>
                            <p class="item-date"><time datetime="2018-03-12T16:00:00.000Z" itemprop="datePublished">2018-03-13</time></p>
                        </div>
                    </li>
                
            </ul>
        </div>
    </div>

    
        
    <div class="widget-wrap">
        <h3 class="widget-title">分类</h3>
        <div class="widget">
            <ul class="category-list"><li class="category-list-item"><a class="category-list-link" href="/categories/QueryDSL-核心技术/">QueryDSL 核心技术</a><span class="category-list-count">7</span></li><li class="category-list-item"><a class="category-list-link" href="/categories/SpringBoot-核心技术/">SpringBoot 核心技术</a><span class="category-list-count">36</span></li></ul>
        </div>
    </div>

    
        
    <div class="widget-wrap">
        <h3 class="widget-title">归档</h3>
        <div class="widget">
            <ul class="archive-list"><li class="archive-list-item"><a class="archive-list-link" href="/archives/2018/04/">四月 2018</a><span class="archive-list-count">3</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2018/03/">三月 2018</a><span class="archive-list-count">4</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2018/01/">一月 2018</a><span class="archive-list-count">1</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2017/12/">十二月 2017</a><span class="archive-list-count">4</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2017/11/">十一月 2017</a><span class="archive-list-count">2</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2017/10/">十月 2017</a><span class="archive-list-count">2</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2017/09/">九月 2017</a><span class="archive-list-count">4</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2017/08/">八月 2017</a><span class="archive-list-count">4</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2017/07/">七月 2017</a><span class="archive-list-count">9</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2017/06/">六月 2017</a><span class="archive-list-count">2</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2017/05/">五月 2017</a><span class="archive-list-count">3</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2017/04/">四月 2017</a><span class="archive-list-count">5</span></li></ul>
        </div>
    </div>

    
        
    <div class="widget-wrap">
        <h3 class="widget-title">标签</h3>
        <div class="widget">
            <ul class="tag-list"><li class="tag-list-item"><a class="tag-list-link" href="/tags/QueryDSL/">QueryDSL</a><span class="tag-list-count">7</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/SpringBoot/">SpringBoot</a><span class="tag-list-count">43</span></li></ul>
        </div>
    </div>

    
        
    <div class="widget-wrap">
        <h3 class="widget-title">标签云</h3>
        <div class="widget tagcloud">
            <a href="/tags/QueryDSL/" style="font-size: 10px;">QueryDSL</a> <a href="/tags/SpringBoot/" style="font-size: 20px;">SpringBoot</a>
        </div>
    </div>

    
        
    <div class="widget-wrap widget-list">
        <h3 class="widget-title">链接</h3>
        <div class="widget">
            <ul>
                
                    <li>
     				<a href="http://hexo.io" target="_blank">Hexo</a>
					</li>
                
            </ul>
        </div>
    </div>


    
    <div id="toTop" class="fa fa-angle-up"></div>
</aside>

				
        </div>
        <!--引入不蒜子-->
<script async src="//dn-lbstatics.qbox.me/busuanzi/2.3/busuanzi.pure.mini.js"></script>
<footer id="footer">
    <div class="outer">
        <div id="footer-info" class="inner">
            <span  id="busuanzi_container_site_pv">本站总访问量<span id="busuanzi_value_site_pv"></span>次</span>
            &copy; 2017 - 2018 恒宇少年 - 版权所有<br>
        </div>
    </div>
</footer>

        


    
        <script src="/libs/lightgallery/js/lightgallery.min.js"></script>
        <script src="/libs/lightgallery/js/lg-thumbnail.min.js"></script>
        <script src="/libs/lightgallery/js/lg-pager.min.js"></script>
        <script src="/libs/lightgallery/js/lg-autoplay.min.js"></script>
        <script src="/libs/lightgallery/js/lg-fullscreen.min.js"></script>
        <script src="/libs/lightgallery/js/lg-zoom.min.js"></script>
        <script src="/libs/lightgallery/js/lg-hash.min.js"></script>
        <script src="/libs/lightgallery/js/lg-share.min.js"></script>
        <script src="/libs/lightgallery/js/lg-video.min.js"></script>
    
    
        <script src="/libs/justified-gallery/jquery.justifiedGallery.min.js"></script>
    
    



<!-- Custom Scripts -->
<script src="/js/main.js"></script>

    </div>
</body>
</html>